package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.entity.ClassQueryParam;
import com.itheima.entity.Clazz;
import com.itheima.entity.Emp;
import com.itheima.entity.PageBean;
import com.itheima.exception.BusinessException;
import com.itheima.mapper.ClassMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;


@Service
public class ClassServiceImpl implements ClassService {

    @Autowired
    private ClassMapper classMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageBean page(ClassQueryParam param) {
        //1.设置分页参数
        PageHelper.startPage(param.getPage(),param.getPageSize());

        //2.调用mapper
        List<Clazz> classList = classMapper.list(param);
        Page p = (Page)classList;
        //3.封装PageBean对象，并返回
        return new PageBean(p.getTotal(),p.getResult());
    }

    /**
     * 添加班级
     * @param clazz
     */
    @Override
    public void add(Clazz clazz) {
        //1.补全创建时间和更新时间
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());

        //2.调用mapper
        classMapper.add(clazz);

    }

    /**
     * 删除班级
     * @param id
     */

    @Override
    public void deleteById(Integer id) {
        //1.判断班级下是否有学生
        Integer count = studentMapper.getByClazzId(id);
        //2.有学生，不能删除
        if(count>0){
            throw new BusinessException("对不起, 该班级下有学生, 不能直接删除");
        }
        //3.无学生，可以删除
        classMapper.deleteById(id);
    }

    /**
     * 根据id查询班级
     * @param id
     * @return
     */
    @Override
    public Clazz selectById(Integer id) {
        Clazz clazz = classMapper.selectById(id);
        return clazz;
    }

    /**
     * 修改班级
     * @param clazz
     */
    @Override
    public void update(Clazz clazz) {
        //更新修改时间
        clazz.setUpdateTime(LocalDateTime.now());
        classMapper.update(clazz);
    }

    /**
     * 查询所有班级
     */
    @Override
    public List<Clazz> selectAll() {
        List<Clazz> clazzs = classMapper.selectAll();
        return  clazzs;
    }

    /**
     * 查询所有员工
     * @return
     */
    @Override
    public List<Emp> selectEmp() {
        List<Emp> emps =classMapper.selectEmp();
        return emps;
    }


}
